﻿//===========================================================================================
// MbCompression, Complete compression library for ASP.NET 2.0-3.5 (VS2005-VS2008)
// Developed by: Miron Abramson. http://blog.mironabramson.com
// Project site: http://www.codeplex.com/MbCompression
// File last update: 14-09-09
//===========================================================================================

#region
using System;
using System.Web;
using System.IO.Compression;
using System.IO;
#endregion

namespace Miron.Web.MbCompression
{
    public sealed class MbCompressionDeflateStream : DeflateStream
    {
        public MbCompressionDeflateStream(Stream stream)
            : base(stream, CompressionMode.Compress)
        {
            _baseStream = stream;
        }
        private Stream _baseStream;
        private bool __isSet = false;
        private bool __isCompressible = false;

        #region Properites

        private bool IsCompressible
        {
            get
            {
                if (!__isSet)
                {
                    if (HttpContext.Current != null &&
                (!Util.IsContentTypeCompressible(HttpContext.Current.Response.ContentType))
                || (HttpContext.Current.Error != null
                || (HttpContext.Current.Response.IsRequestBeingRedirected && Util.IsMsAjaxRequest(HttpContext.Current))))
                    {
                        __isCompressible = false;
                    }
                    else
                    {
                        __isCompressible = true;
                    }
                    __isSet = true;
                }
                return __isCompressible;
            }
        }

        public override bool CanRead
        {
            get { return base.CanRead; }
        }

        public override bool CanSeek
        {
            get { return base.CanSeek; }
        }

        public override bool CanWrite
        {
            get { return base.CanWrite; }
        }

        public override void Flush()
        {
            if (!IsCompressible)
            {
                _baseStream.Flush();
                return;
            }

            base.Flush();
        }

        public override long Length
        {
            get { return base.Length; }
        }

        public override long Position
        {
            get { return base.Position; }
        }

        #endregion

        #region Methods

        public override void Write(byte[] buffer, int offset, int count)
        {
            if (!IsCompressible)
            {
                HttpContext.Current.Items.Remove("preferredEncoding");
                _baseStream.Write(buffer, offset, count);
                return;
            }

            base.Write(buffer, offset, count);
        }


        #endregion
    }
}